package com.techstar.ats.netty.handler;

import lombok.extern.slf4j.Slf4j;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import com.techstar.ats.MessageType;
import com.techstar.ats.dxp.live.req.F01MessagePolling;

@Slf4j
public class KeepAliveHandler extends ChannelInboundHandlerAdapter {
	private int keepAlive;

	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		this.keepAlive = 0;
		super.channelRead(ctx, msg);
	}

	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if(evt instanceof IdleStateEvent) {
			if(IdleState.WRITER_IDLE == ((IdleStateEvent) evt).state()) {
				F01MessagePolling req = new F01MessagePolling();
				req.id = MessageType.MESSAGE_POLLING.value();
				ctx.writeAndFlush(req);
			}

			if(IdleState.READER_IDLE == ((IdleStateEvent) evt).state() && this.keepAlive++ > 3) {
				log.warn("Not yet received the test frame, disconnect {}", ctx.channel());
				ctx.close();
			}
		}

		super.userEventTriggered(ctx, evt);
	}
}
